package links

import (
	"encoding/json"
	"fmt"
	apis2 "gluenet/pkg/apis"
	"gluenet/pkg/meta"
	glue2 "gluenet/pkg/platform/glue"
	v1 "gluenet/utils/rpc/labels"
	"gopkg.in/yaml.v3"
	"strings"
)

func LinkStrategyApplication(ctx *apis2.GlueContext) {
	var (
		err  error
		data = struct {
			StrategyGuid     string   `json:"strategy_guid" yaml:"strategy_guid"`
			ApplicationGuids []string `json:"application_guids" yaml:"application_guids"`
		}{}
	)
	if err = ctx.WebContext.ReadJSON(&data); err != nil {
		ctx.Logger.Errorf("read json error %v", err)
		ctx.WebContext.JSON(apis2.ResponseReqErr(fmt.Errorf("read json  error:%v", err), nil))
		return
	}

	ctx.Logger.Debugf("get agent guid: %v", data)

	// 校验：
	// 。。。
	var ins []meta.Instance
	for _, appGuid := range data.ApplicationGuids {

		var app *meta.Instance
		if err = ctx.DataBase.InstanceGet(appGuid, &app); err != nil {
			ctx.Logger.Errorf("app guid not exist %v", err)
			ctx.WebContext.JSON(apis2.ResponseReqErr(fmt.Errorf("app guid not exist %v", err), nil))
			return
		}
		ins = append(ins, *app)
	}

	var sins *meta.Instance
	if err = ctx.DataBase.InstanceGet(data.StrategyGuid, &sins); err != nil {
		ctx.Logger.Errorf("strategy guid not exist %v", err)
		ctx.WebContext.JSON(apis2.ResponseReqErr(fmt.Errorf("strategy guid not exist %v", err), nil))
		return
	}
	if sins.Platform != apis2.PlatfromGluenets {
		ctx.Logger.Errorf("strategy plat only support gluenets")
		ctx.WebContext.JSON(apis2.ResponseReqErr(fmt.Errorf("strategy plat only support gluenets"), nil))
		return
	}
	var st glue2.Instance
	if err = json.Unmarshal([]byte(sins.InstanceValue), &st); err != nil {
		ctx.Logger.Errorf("strategy instance value decode %v", err)
		ctx.WebContext.JSON(apis2.ResponseReqErr(fmt.Errorf("strategy instance value decode %v", err), nil))
		return
	}

	var cts glue2.Containers
	if err = yaml.Unmarshal([]byte(st.InstanceYaml), &cts); err != nil {
		ctx.Logger.Errorf("strategy instance decode %v", err)
		ctx.WebContext.JSON(apis2.ResponseReqErr(fmt.Errorf("strategy instance decode %v", err), nil))
		return
	}

	// 发送给策略
	for k := range cts.Containers {
		ctx.Logger.Debugf("request topic %v", strings.Join([]string{data.StrategyGuid, v1.StrategyControlApplicationSet}, ":"))
		guid := strings.Join([]string{data.StrategyGuid, k}, "_")
		bts, _ := json.Marshal(apis2.IRequest{Data: ins})
		if _, err = ctx.Rpc.Request(strings.Join([]string{guid, v1.StrategyControlApplicationSet}, ":"), bts); err != nil {
			ctx.Logger.Errorf("set info to strategy error %v", err)
			ctx.WebContext.JSON(apis2.ResponseReqErr(fmt.Errorf("set info to strategy error:%v", err), nil))
			return
		}
	}

	//更新数据
	//orm2.SaveStrategyLinks(ctx, data.StrategyGuid, meta.EnCodeLinks(data.ApplicationGuids))
	ctx.DataBase.StrategyLinksPut(&meta.StrategyLinks{
		StrategyGuid:     data.StrategyGuid,
		ApplicationGuids: meta.EnCodeLinks(data.ApplicationGuids),
	})
	//if len(ags) == 0 {
	//	ctx.Logger.Warnf("data is nil", err)
	//	ctx.WebContext.JSON(apis.ResponseOK(nil))
	//	return
	//}

	//返回结果
	n, _ := ctx.WebContext.JSON(apis2.ResponseOK(nil))
	ctx.Logger.Debugf("list config response bytes: %v", n)
}
